package com.jinlejia.erp.widget.image;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import androidx.fragment.app.Fragment;

import java.lang.ref.WeakReference;


abstract class Host<T> extends WeakReference<T> {
    private Host(T referent) {
        super(referent);
    }

    abstract boolean isAlive();

    abstract Context context();

    static Host create(Context context){
        if (context instanceof Activity){
            return new ActivityHost((Activity) context);
        }
        throw new IllegalArgumentException("非法访问");
    }

    static Host create(Fragment fragment){
        return new FragmentHost(fragment);
    }

    final static class FragmentHost extends Host<Fragment>{

        private FragmentHost(Fragment referent) {
            super(referent);
        }

        @Override
        boolean isAlive() {
            Fragment fragment = get();
            if (fragment==null)return false;
            fragment.getActivity();
            return false;
        }

        @Override
        Context context() {
            Fragment fragment = get();
            if (fragment==null)return null;
            return fragment.getContext();
        }
    }


    final static class ActivityHost extends Host<Activity>{

        private ActivityHost(Activity referent) {
            super(referent);
        }

        @Override
        public boolean isAlive() {
            Activity activity = get();
            if (activity==null)return false;
            if (activity.isFinishing()){
                return false;
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                if (activity.isDestroyed()){
                    return false;
                }
            }
            return true;
        }

        @Override
        Context context() {
            return get();
        }
    }
}
